package pilgun.Multithread.Sum;

import java.util.Arrays;
import java.util.Scanner;

import static java.lang.Math.*;


public class Summa {
	private static int THREAD_NUM = 10;
	private static float N = 2.0f;
	
	private static volatile double sum = 0;
	private static boolean[] finished = new boolean[THREAD_NUM];
	
	private static boolean allFinished(){	
		for (boolean f : finished){
			if (!f){
				return false;
			}
		}
		return true;
	}
	
	static class CalcSum implements Runnable{
		private float lowBound, highBound;
		private double localSum = 0;
		private int count = 0;
		private static final float STEP = 0.0001f;
		private int threadNum;
		
		
		private static float round (float num){
			return (float) floor(Math.round(1/STEP)*num)/Math.round(1/STEP); 
		}
		
		
		CalcSum(float lowBound, float highBound, int num, boolean includeLastPoint){
			this.lowBound = round(lowBound);
			if (!includeLastPoint){
				this.highBound = round(highBound);
			}
			else{
				this.highBound = round(highBound) + STEP;
			}
			threadNum = num;
		}
		
		public void run(){
			double last = 0;
			for (double x = lowBound; abs(highBound-x)>=STEP/2; x+=STEP){
				localSum += sin(x)*cos(x);
				//System.out.printf("\nx: %f localSum: %f", x, localSum);
				count++;
				last = x;
			}
			
			sum += localSum;
			finished[threadNum] = true;
			System.out.printf("\nlow: %f high: %f localSum: %f", lowBound, highBound, localSum);
		}
	}

	public static void main(String[] args) throws InterruptedException{
		
		float inc = 2*(N)/THREAD_NUM;;
		boolean includeLast = false;
		for (int i=0; i<THREAD_NUM; i++){
			if (i ==THREAD_NUM-1){
				includeLast = true;
			}
			new Thread(new CalcSum(-N + i*inc, -N + (i+1)*inc, i, includeLast)).start();
		}		
		while (!allFinished()){
		}
		
		Thread.sleep(100);
		System.out.println("\nsum: " +sum);
	}
}